﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IMLibrary.Controls.ListBoxex;

namespace OurMsg.Controls
{
    public partial class InviteFriendAddRoom : UserControl
    {
        public InviteFriendAddRoom()
        {
            InitializeComponent();
            treeView_Organization.NodeMouseDoubleClick += (treeView_Organization_NodeMouseDoubleClick);
            listBoxEx1.DoubleClick += new EventHandler(listBoxEx1_DoubleClick);
        }

         
        void listBoxEx1_DoubleClick(object sender, EventArgs e)
        {
            if (listBoxEx1.SelectedItem != null)
            {
                AddedUsers.Remove(((listBoxEx1.SelectedItem as ListBoxExItem).Tag as ExUser).UserID);
                listBoxEx1.Items.Remove(listBoxEx1.SelectedItem as ListBoxExItem);
            }
        }

        List<UInt32> AddedUsers = new List<UInt32>();

        void treeView_Organization_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag is ExUser)
            {
                var user = (e.Node.Tag as ExUser);
                if (IsExsit(user.UserID)) return;

                ListBoxExItem item = new ListBoxExItem();
                item.Image = imageList1.Images[e.Node.ImageIndex];
                item.Text = user.UserName + "(" + user.UserID + ")";
                item.Tag = e.Node.Tag;
                listBoxEx1.Items.Add(item);
                AddRoomExsitUser(user.UserID); 
            }
        }



        /// <summary>
        /// 获得邀请的用户帐号（用分号隔开）
        /// </summary>
        /// <returns></returns>
        public string GetUsersID()
        {
            string s = "";
            foreach (ListBoxExItem item in this.listBoxEx1.Items)
            {
                ExUser user = item.Tag as ExUser;
                s += user.UserID +",";
            }
            return s;
        }

        public void AddRoomExsitUser(UInt32 userID)
        {
            if (!IsExsit(userID))
                AddedUsers.Add(userID);
        }

        /// <summary>
        /// 判断用户是否已经在群
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        private bool IsExsit(UInt32 userID)
        {
            foreach (var uid in AddedUsers)
                if (uid == userID)
                    return true;
            return false;
        }

        #region 私有方法
        /// <summary>
        /// 
        /// </summary>
        ExGroup[] Groups;
        /// <summary>
        /// 
        /// </summary>
        ExUser[] Users;
        /// <summary>
        /// 我的好友
        /// </summary>
        TreeNode MyFriendNode;

        #region 加载本地数据库中的组织机构过程
        private delegate void delegateLoadLocalOrg();//委托代理
        /// <summary>
        /// 加载本地数据库中的组织机构
        /// </summary>
        public  void LoadUsers()
        {
            treeView_Organization.Nodes.Clear();

            addGroupToTreeView(treeView_Organization);
            addUserToTreeView();
        }
        #endregion

        #region 在treeView中添加分组groups集合并返回 TreeNode
        /// <summary>
        /// 在treeView中添加分组groups集合并返回 TreeNode
        /// </summary>
        /// <param name="treeView1"></param>
        /// <param name="groups"></param>
        /// <returns></returns>
        private void addGroupToTreeView(TreeView tv)
        {
            //{
            //    var group = new ExGroup() { GroupID = -1, GroupName = "我的好友",SupGroupID =-1 };
            //    Groups[Groups.Length - 1] = group;
            //}

            ///添加根分组节点
            {
                var group = new ExGroup() { GroupID = -1, GroupName = "我的好友" };
                MyFriendNode = new TreeNode();
                MyFriendNode.Text = group.GroupName;
                MyFriendNode.ToolTipText = group.GroupName;
                MyFriendNode.ImageIndex = 1;
                MyFriendNode.SelectedImageIndex = 1;
                MyFriendNode.Tag = group;
                group.Tag = MyFriendNode;
                MyFriendNode.Text = group.GroupName + "[0]";
                tv.Nodes.Add(MyFriendNode);
            }

            if (Global.Groups.Count == 0) return;
            Groups = new ExGroup[Global.Groups.Count];
            Global.Groups.Values.CopyTo(Groups, 0);
            foreach (ExGroup group in Groups)
                if (findGroup(group.SupGroupID) == null)
                {
                    TreeNode node = new TreeNode();
                    node.Text = group.GroupName;
                    node.ToolTipText = group.GroupName;
                    node.ImageIndex = 1;
                    node.SelectedImageIndex = 1;
                    node.Tag = group;
                    group.Tag = node;
                    node.Text = group.GroupName + "[0]";
                    tv.Nodes.Add(node);
                }

            bool t = false;
            ExGroup parentGroup;
            int rCount = 0;
            int sqrCount = (Groups.Length * Groups.Length);//最大循环次数

            while (!t && rCount <= sqrCount)//如果查询还未结束且循环次数没有超过部门数n平方，则继续
            {
                t = true;
                foreach (ExGroup group in Groups)
                {
                    parentGroup = findGroup(group.SupGroupID);//找到上级部门节点
                    if (parentGroup != null && group.Tag == null) //如果要添加的部门节点不是根部门节点且此节点还未添加 
                    {
                        if (parentGroup.Tag != null)// 当前的上级部门已经添加时，添加部门  
                        {
                            TreeNode node = new TreeNode();
                            node.Text = group.GroupName;
                            node.ToolTipText = group.GroupName;
                            node.ImageIndex = 1;
                            node.SelectedImageIndex = 2;
                            node.Tag = group;
                            group.Tag = node;
                            (parentGroup.Tag as TreeNode).Nodes.Add(node);
                        }
                        else//如果当前部门节点的上级部门不是根部门节点并且上级部门的上级部门还未添加，则添加不成功，循环后再添加
                        {
                            t = false;
                        }
                    }
                    rCount++;//查询次数增1，如果大于部门n平方还未结束，则强行结束
                }
            }
        }
        #endregion

        #region 在treeView中的groups中添加用户
        /// <summary>
        /// 在treeView中的groups中添加用户
        /// </summary>
        /// <param name="groups"></param>
        /// <param name="users"></param>
        private void addUserToTreeView()
        {
            if (Global.Users.Count == 0) return;
            if (treeView_Organization.Nodes.Count == 0) return;
            Users = new ExUser[Global.Users.Count];
            Global.Users.Values.CopyTo(Users, 0);

            foreach (ExUser user in Users)
            {
                TreeNode node = new TreeNode();
                node.Text = user.UserName + "(" + user.UserID + ")"; ;
                node.ToolTipText = user.UserName;
                node.ImageIndex = 0;
                node.SelectedImageIndex = 0;
                node.Tag = user;

                ExGroup group = findGroup(user.GroupID);
                if (group != null && group.Tag != null)
                { 
                    TreeNode gNode = group.Tag as TreeNode;
                    if (gNode != null)
                    {
                        gNode.Nodes.Add(node);
                        gNode.Text = (gNode.Tag as ExGroup).GroupName + "[" + gNode.Nodes.Count + "]";
                    }
                }
                else
                {
                    MyFriendNode.Nodes.Add(node);
                    MyFriendNode.Text = (MyFriendNode.Tag as ExGroup).GroupName + "[" + MyFriendNode.Nodes.Count + "]";
                }
            }
        }
        #endregion

        #region 查找组
        /// <summary>
        /// 查找组
        /// </summary>
        /// <param name="GroupID"></param>
        /// <returns></returns>
        private ExGroup findGroup(Int32 GroupID)
        {
            if (Groups == null) return null;
            foreach (ExGroup group in Groups)
                if (group.GroupID == GroupID)
                    return group;
            return null;
        }
        #endregion

        #region 查找用户
        /// <summary>
        /// 查找用户
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="users"></param>
        /// <returns></returns>
        private ExUser findUser(UInt32 userID)
        {
            if (Users == null) return null;
            foreach (ExUser user in Users)
                if (user.UserID == userID)
                    return user;
            return null;
        }
        #endregion

        #endregion
    }
}
